package com.lmb.lnterceptor;

import cn.hutool.json.JSONUtil;
import com.lmb.util.Result;
import com.lmb.util.SyS;
import com.lmb.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

//拦截器
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求的url
        String token=request.getHeader(SyS.TOKEN_AUTHORIZATION);
        String requestUri = request.getRequestURI();
        //判断token是否存在且有效
        if (token==null||!TokenUtil.verify( token)){
//            response.setStatus(401);
            Result result=new Result(401,"认证异常",null);//封装结果
            //hutool
            String json= JSONUtil.toJsonStr(result);
            //fastjson
//            json= JSON.toJSONString(result);
            response.getWriter().print(json);//返回结果
            return false;//拦截
        }


        //返回结果
        return true;//放行
    }
}
